package com.github.boluo1230.wechat.service.mp.impl;

import com.github.boluo1230.wechat.constant.WeixinConstant;
import com.github.boluo1230.wechat.dao.MpAppDao;
import com.github.boluo1230.wechat.entity.EventMessage;
import com.github.boluo1230.wechat.entity.MpApp;
import com.github.boluo1230.wechat.entity.vo.WxAccessToken;
import com.github.boluo1230.wechat.feign.WxAccessTokenAPI;
import com.github.boluo1230.wechat.service.mp.*;
import com.github.boluo1230.wechat.util.WeixinUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.TreeMap;

/**
 * @author Code Farmer
 * @date 2019/10/12 20:59
 */
@Service
public class WeChatServiceImpl implements WeChatService {

    @Autowired
    private MpAppDao mpAppDao;
    @Autowired
    private WxUserService wxUserService;
    @Autowired
    private QrAutoReplyService qrAutoReplyService;
    @Autowired
    private AutoReplyService autoReplyService;
    @Autowired
    private MpAppService mpAppService;
    @Autowired
    private RedisService redisService;
    @Autowired
    private WxAccessTokenAPI wxAccessTokenAPI;

    @Override
    public String handle(String requestBody, MpApp mpApp) throws Exception {
        Map<String, String> requestMap = WeixinUtil.xmlString2Map(requestBody);
        EventMessage message = new EventMessage(requestMap);

        String openId = message.getFromUserName();
        String event = message.getEvent();
        wxUserService.recordUserInfo(mpApp, openId, event);//
        if (message.getMsgType().equals("text")
                && message.getContent().toLowerCase().replace("/ /g", "").equals("showmyopenid")) {
            //TODO 返回openId
        }

        if (this.handleService(mpApp.getServiceUrl(), message)) {
            return "success";
        }

        if (StringUtils.isNotBlank(message.getEvent()) && message.getEvent().equals("VIEW")) {//处理菜单事件

        }

        boolean replyFlag = qrAutoReplyService.handleQrAutoReply(message, mpApp);
        if (!replyFlag) {
            System.out.println("关键词回复");
            replyFlag = autoReplyService.handleAutoReply(message, mpApp);
        }

        if (StringUtils.isNotBlank(message.getEvent()) && StringUtils.isNotBlank(message.getEventKey())
                && message.getEventKey().equals("") && message.getEvent().equals("subscribe")) {
            message.setContent("subscribe");
            message.setMsgType("text");
            replyFlag = autoReplyService.handleAutoReply(message, mpApp);   //转换为客服消息回复
            return "";
        }

        if (replyFlag) {
            return "";
        }

        return "success";

    }

    @Override
    public WxAccessToken getAccessToken(String appId, String type, String signature) {
        MpApp mpApp = mpAppService.findMpApp(appId);
        if (mpApp == null) {
            return new WxAccessToken(10001, "auth fail");
        }
        TreeMap<String, String> params = new TreeMap<>();
        params.put("appId", appId);
        params.put("type", type);

        if (!WeixinUtil.checkSignature(params, signature, WeixinConstant.ACCESS_TOKEN_KEY)) {
            return new WxAccessToken(10001, "auth fail");
        }

        WxAccessToken wxAccessToken = redisService.getAccessToken(appId);
        if (wxAccessToken == null) {
            wxAccessToken = wxAccessTokenAPI.getAccessToken("client_credential", appId, mpApp.getAppSecret());
            if (wxAccessToken.getErrno() == 0) {
                wxAccessToken.setErrmsg("success");
            }
            redisService.setAccessToken(appId, wxAccessToken);
        }
        return wxAccessToken;
    }

    private boolean handleService(List<String> serviceUrl, EventMessage message) {
        if (serviceUrl == null) {
            return false;
        }
        for (String s : serviceUrl) {
            boolean handleRes = this.requestServiceHandle(s, message);
            if (handleRes) { //used ：0继续放下走；1到此为止
                return true;
            }
        }
        return false;
    }

    //todo
    private boolean requestServiceHandle(String serviceUrl, EventMessage message) {

        return true;
    }

}
